package com.fengmi.security;

import cn.hutool.json.JSONUtil;
import com.fengmi.vo.ResultVO;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 123
 * @Date 2022/2/9 20:37
 * @Version 1.0
 */
/**
 * 自定义403异常处理，重写SpringSecurity中的ExceptionTranslationFilter
 * 实现AccessDeniedHandler接口
 */
//@Component
public class MyAccessDenied implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        //设置响应数据格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //输入响应内容
        PrintWriter writer = null;
        try {
            writer = httpServletResponse.getWriter();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        ResultVO resultVO = new ResultVO(false, "没有权限访问");
        resultVO.setCode("403");
        writer.write(JSONUtil.toJsonPrettyStr(resultVO));
        writer.flush();

    }
}
